/*选人组件*/
import { Modal, Select,  Button, Tooltip, Tag} from "antd";
import { forwardRef, useState ,useRef, useEffect} from "react";
import message from "../../framework/common/utils/message";
import {buildUrl} from "../../framework/common/utils"
import clsx from "clsx";
import { useForm } from "../../framework/common/context/metadata-context";

export default forwardRef(function({
    className,
    package_id="", 
    urlPrefix="",
    multiSelect = false,
    filter="",//组织范围 公司或者全部
    onlyend=0,//仅选择末级组织
    source_type="",//数据源类型
    configs="",//sql数据源
    classify_id="",
    business_id="",
    textField = "org_name",//实际请求返回的text Key
    valueField = "org_id",//时期静秋返回的id key
    titleField="org_path",
    value=[], 
    placeholder="请选择组织",//为空提示语
    onChange,
    title="选择组织",
    popupContainer=()=>{
      return document.querySelector(".main-content")
    },//toolTip出现的位置
    maxSize = 30//最大可选数量
  }, ref) {
  const [isVisible, setIsVisible] = useState(false);//选人弹出框显示状态  
  const selectRef = useRef(null);

  /*显示选人弹出框 */
  function showModal(){
    selectRef.current.blur();
    setIsVisible(true);
  }

  //使用了ant select组件，返回空的下拉对象
  function getList(){
    return <></>
  }

  //自定义右侧 + 按钮
  function addIcon(){
    return <span className="add_icon"></span>
  }
  
  const [selectValue, setSelectValue] = useState([]);//ant select组件需要的值
  const [fieldData, setFieldData] = useState([]);//当前组件需要的值

  //设置select的value
  function setValue(data){
    if(data.length <= 0){
      setSelectValue([]);//更新select的显示值
      setFieldData([]);//更新组件自身需要的值
    }else{
      let returnData = [];
      data.forEach(function(item){
        returnData.push({
          value: item,
          label: item[textField],
          key: item[valueField]
        },
        );//select要返回文本，所以实际显示文本
      })
      setSelectValue(returnData);//更新select的显示值
      setFieldData(data);//更新组件自身需要的值
    }
  }//设置实际值

  useEffect(function(){
    setValue(value);//初始化设置默认值
  },[]);

  /**
   * 弹出框更新数据
   * fieldData 实际字段要的值
   */
  function setData(fieldData){
    //根据textField valueField再重新包装一下后端需要的key
    fieldData = fieldData.map(function (item) {
      item[textField] = item.name;
      item[valueField] = item.guid;
      item[titleField] = item.path;
      return {
        ...item
      }
    });
    setValue(fieldData);//设置select组件的值
    onChange?.(fieldData);//更新外部表单字段的值
  }
  function handleChange(val, options) {
    var fieldData = [];
    val.map(function(item){
      fieldData.push(item.value);
    });
    setValue(fieldData);//设置select组件的值
    onChange?.(fieldData);//更新外部表单字段的值
  }

  return <>
    {
      isVisible
      && <ModalContent 
          title={title}
          business_id={business_id}
          filter={filter}
          onlyend={onlyend}
          source_type={source_type}
          configs={configs}
          classify_id={classify_id}
          valueField={valueField}
          textField={textField}
          maxSize={multiSelect ? maxSize : 1}
          package_id={package_id} 
          urlPrefix={urlPrefix} 
          isVisible={isVisible} 
          multiSelect={multiSelect}
          setIsVisible={setIsVisible}
          fieldData={fieldData}
          setData={setData}></ModalContent>
    }
    <Select ref={selectRef}
      className={clsx("person-select", className)}
      value={selectValue}
      onChange={handleChange}
      labelInValue
      optionLabelProp="station_name"
      dropdownRender={()=>{return getList()}}
      dropdownClassName={"person-select-dropdown"}
      mode="tags"
      style={{ width: '100%' }}
      placeholder={placeholder}
      suffixIcon={addIcon()}
      showArrow = {true}
      tagRender={(props)=>{
        return TagRender({
          popupContainer: popupContainer,
          props: props//ant tagRender自带的参数
        });
      }}
      onClick={()=>{showModal()}}
      options={[]}
    >
    </Select>
  </>

})

const ModalContent = forwardRef(function ModalContent({
  isVisible, 
  business_id,
  setIsVisible, 
  setData, 
  package_id, 
  urlPrefix,
  multiSelect,
  filter,//组织范围 公司或者全部
  onlyend,//仅选择末级组织
  source_type,//数据源类型
  configs,//sql数据源
  classify_id,
  textField,//实际请求返回的text Key
  valueField,//时期静秋返回的id key
  titleField,
  value, 
  placeholder,//为空提示语
  onChange,
  fieldData,//组件自己需要的值
  title,
  maxSize//最大可选数量
}, ref) {
  const { data: tplData, params, csrfToken } = useForm().root;
  const iframeRef = useRef(null);

  function handleOk(option) {

    //测试用的返回数据
    //   let selectData = [
    //     {
    //       code: "duying",
    //       guid: "08DA2692-644A-424F-8451-A473EE19BCA1",
    //       name: "杜英",
    //       station_guid: "08DA2434-2758-4CA3-8D32-212B10CCDBE8",
    //       station_name: "科技园区/深圳湾科技发展有限公司/深圳湾科技发展有限公司（本部）/生态运营中心/招商运营部",
    //     }
    //   ]
    let selectData = [];
    if(option.backNull === true){
      //返回空值
    }else{
      selectData = iframeRef.current.contentWindow.window.getData();
    }
    if(selectData.length > maxSize){
      message.info({
        content: "最多允许" + maxSize + "个选项"
      })
    }else{
      setData(selectData);
      setIsVisible(false);
    }
  }
  const handleCancel = () => {
    setIsVisible(false);
  };
  
  //组件配置项
  let options={
    multiSelect: multiSelect ? 1 : 0,//是否多选
    package_id: package_id,
    business_id: business_id,
    onlyend: onlyend,//是否末级
    classify_id: classify_id,
    filter: filter,//组织范围
  }

  window.orgSqlConfg = null;//sql模式，弹出框内需要这个参数
  
  if(source_type == "sql"){//数据库类型
    options.filter = "";//清空filter属性

    let orgData = {
      sql: configs,
      filter: {}
    }

    configs.replace(/\[(.*?)\]/g,function(all, key) {
      var _value = tplData.form.form_data.main[key];
      if(_value === null || _value === undefined || _value === ""){//如果当前值为空，则赋值为空
          _value = "";
      }
      orgData.filter[key] = _value;
    })

    window.orgSqlConfg = orgData;
  }

  let _openUrl = '/flowinstance/process/select-orgs';
  if (urlPrefix) {
    _openUrl = urlPrefix + _openUrl;
  }
  _openUrl = buildUrl(_openUrl, options);//给链接拼接配置项

  //每次打开前，给当前window增加orgs，用于弹出框回填
  if (fieldData && fieldData.length) {
      fieldData.forEach(function (item) {
          item.guid = item[valueField];
          item.name = item[textField];
      });
      window.orgs = fieldData;
  } else {
      window.orgs = null;
  }

  let modalWidth = multiSelect ? 720 : 400;

  return (
    <Modal 
      bodyStyle={{padding:0}} 
      centered={true} 
      title={title} 
      width={modalWidth} 
      visible={isVisible} 
      onCancel={()=>{
        setIsVisible(false)
      }}
      footer={[
        <Button key="back" className="float-left" onClick={()=>{handleOk({backNull: true})}}>返回空值</Button>,
        <Button key="cancel" onClick={handleCancel}>取消</Button>,
        <Button key="submit" type="primary" onClick={handleOk}>确定</Button>,
      ]}
    >
      <iframe 
        ref = {iframeRef}
        src={_openUrl}
        style={{"width":"100%","height": (600-54-52)+"px"}}
      ></iframe>
    </Modal>
  );
});

//自定义select的tage
function TagRender ({
  props,//ant组件自带参数
  popupContainer//提示出现的位置
}) {
  const { label, value, closable, onClose } = props;
  return <Tooltip
            getPopupContainer={popupContainer}
            placement="bottom" 
            color="white"
            title={
              ()=>{
                return <div
                          onClick={
                            (e) => {
                              e.stopPropagation();//提示内容阻止冒泡，防止触发了tag的点击事件导致出现弹框
                            }
                          }
                          onMouseDown={(e) => {
                            e.stopPropagation();//提示内容阻止冒泡，防止触发了tag的禁止选中文本事件
                          }}
                        >
                          {value.org_path || value.path || label}
                        </div>
              }
            }
          >
            <Tag
              closable={closable}
              className="text-sm mysoft-tag-connect"
              onClose={onClose}
            >
              {label}
            </Tag>
          </Tooltip>;
};